package com.xinqi.modules.mq.delay.dao;

import com.xinqi.modules.mq.delay.entity.MqDelayMessageEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;

@Repository
@RequiredArgsConstructor
public class MqDelayMessageRepository {

    private final JdbcTemplate jdbcTemplate;

    /**
     * 添加数据
     */
    public void insert(String mqId, String mqKey, LocalDateTime arrivalTime) {
        String sql = "INSERT INTO mq_delay_message (create_time, update_time, mq_id, mq_key, arrival_time, status, is_del) " +
            "VALUES (now(), now(), ?, ?, ?, 0, 0)";
        jdbcTemplate.update(sql, mqId, mqKey, arrivalTime);
    }

    /**
     * 删除数据
     */
    public void deleteById(Long id) {
        String sql = "DELETE FROM mq_delay_message WHERE id = ?";
        jdbcTemplate.update(sql, id);
    }

    /**
     * 删除数据
     */
    public int deleteByKey(String key) {
        String sql = "DELETE FROM mq_delay_message WHERE mq_key = ?";
        return jdbcTemplate.update(sql, key);
    }

    /**
     * 更新数据
     */
    public int updateIsDel(String key) {
        String sql = "UPDATE mq_delay_message SET update_time = ?, is_del = 1 WHERE is_del = 0 and mq_key = ?";
        return jdbcTemplate.update(sql, LocalDateTime.now(), key);
    }

    /**
     * 更新数据
     */
    public int updateStateByMqId(String id) {
        String sql = "UPDATE mq_delay_message SET update_time = ?, status = 1 WHERE is_del = 0 and mq_id = ?";
        return jdbcTemplate.update(sql, LocalDateTime.now(), id);
    }

    /**
     * 查询数据
     */
    public MqDelayMessageEntity findByMqId(String mqId) {
        String sql = "SELECT * FROM mq_delay_message WHERE mq_id = ?";
        return jdbcTemplate.queryForObject(sql, new MqDelayMessageRowMapper(), mqId);
    }

    /**
     * 判断数据是否存在
     */
    public Boolean checkDel(String mqId) {
        String sql = "SELECT count(*) FROM mq_delay_message WHERE mq_id = ? and is_del = 1";
        Long count = jdbcTemplate.queryForObject(sql, Long.class, mqId);
        return count != null && count > 0;
    }
}
